package productConsumer;

/**
 * 原始版本的同步控制
 */
public class demo3 {
    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                try {
                    data.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程A").start();

        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                try {
                    data.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程B").start();

        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                try {
                    data.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程C").start();

        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                try {
                    data.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程D").start();
    }
}

class Data{
    private int num = 0;

    public synchronized void increase() throws InterruptedException {
        while (num != 0){
            this.wait();
        }

        num++;

        System.out.println("当前线程："+Thread.currentThread().getName()+" num:"+num);

        this.notifyAll();
    }

    public synchronized void decrease() throws InterruptedException {
        while (num == 0){
            this.wait();
        }
        num--;
        System.out.println("当前线程："+Thread.currentThread().getName()+" num:"+num);

        this.notifyAll();
    }
}